//
//  ECSelectTagView.m
//  ECERP.CRM
//
//  Created by 刘思麟 on 2018/10/26.
//  Copyright © 2018年 Mac. All rights reserved.
//

#import "ECSelectTagView.h"

@interface ECSelectTagView()

@property (nonatomic,strong) NSMutableArray<UIButton*> * tagBts;

@end

@implementation ECSelectTagView

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.tagBts = @[].mutableCopy;
        self.itemBorderWidth = 0.5 * PX_RELATIVE375;
        self.itemHeight = 24 * PX_RELATIVE375;
        self.itemBorderColor = ECCOLOR(0x999999);
        self.intervalBetweenItmeH = 8 * PX_RELATIVE375;
        self.intervalBetweenItmeV = 12 * PX_RELATIVE375;
        self.retractTop = self.retractLeft = 12 * PX_RELATIVE375;
    }
    return self;
}

- (void)setItemBorderColor:(UIColor *)itemBorderColor {
    _itemBorderColor = itemBorderColor;
    for (UIButton * bt in self.tagBts) {
        bt.layer.borderColor = itemBorderColor.CGColor;
    }
}

- (void)setItemBorderWidth:(CGFloat)itemBorderWidth {
    _itemBorderWidth = itemBorderWidth;
    for (UIButton * bt in self.tagBts) {
        bt.layer.borderWidth = itemBorderWidth;
    }
}

- (void)layoutSubviews {
    [super layoutSubviews];
    CGFloat x = self.retractLeft;
    CGFloat y = self.retractTop;
    for (UIButton * bt in self.tagBts) {
        if (self.itemBorderColor) {
            bt.layer.borderColor = self.itemBorderColor.CGColor;
        }
        if (self.itemBorderWidth) {
            bt.layer.borderWidth = self.itemBorderWidth;
        }
        
        if (x + bt.width > self.width - self.retractLeft * 2) {
            x = self.retractLeft;
            y += self.itemHeight + self.intervalBetweenItmeV;
        }
        
        bt.frame = CGRectMake(x, y, bt.width, self.itemHeight);
        
        x = bt.right + self.intervalBetweenItmeH;
        bt.layer.cornerRadius = self.itemHeight / 2;
        if (bt == self.tagBts.lastObject) {
            self.height = bt.bottom + 12 * PX_RELATIVE375;
        }
    }
}

- (void)setTagStrs:(NSMutableArray<NSString *> *)tagStrs {
    _tagStrs = tagStrs;
    for (NSString * str in _tagStrs) {
        UIButton * bt = [self creatBtWithTitle:str];
        [self addSubview:bt];
        [self.tagBts addObject:bt];
    }
    [self setNeedsLayout];
}

- (UIButton *)creatBtWithTitle:(NSString*)title {
    UIButton * bt = [UIButton buttonWithType:UIButtonTypeCustom];
    bt.clipsToBounds = YES;
    [bt setTitle:title forState:UIControlStateNormal];
    bt.titleLabel.font = ECFONT(12 * PX_RELATIVE375);
    [bt setTitleColor:ECCOLOR(0x999999) forState:UIControlStateNormal];
    CGSize size = [title sizeForFont:bt.titleLabel.font size:CGSizeMake(0, self.itemHeight) mode:NSLineBreakByWordWrapping];
    bt.bounds = CGRectMake(0, 0, size.width + self.itemHeight / 2 , self.itemHeight);
    return bt;
}


@end
